//
//  PKLoginViewController.m
//  PianKe
//
//  Created by lanou on 15/12/24.
//  Copyright © 2015年 KFC. All rights reserved.
//

#import "PKLoginViewController.h"
#import "PKLTView.h"
#import "PKRegistViewController.h"
#import "UMSocialControllerService.h"
#import "PKPersonModel.h"
@interface PKLoginViewController ()

@property (strong, nonatomic) PKLTView *emailbox;

@property (strong, nonatomic) PKLTView *password;


@property (strong, nonatomic) PKPersonModel *model;
@property (assign, nonatomic) BOOL isFailed;
@end

@implementation PKLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 自己在导航栏的位置处加返回按钮
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(10 * kWidthBase, 30 * kHeightBase, 30*kWidthBase, 30 * kHeightBase);
    [backButton setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:(UIControlStateNormal)];
    [self.view addSubview:backButton];
    [backButton addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
  
#pragma mark - 邮箱
    _emailbox = [[PKLTView alloc]initWithFrame:CGRectMake(0 - (kScreenWidth - 120 * kWidthBase), 260 * kHeightBase, kScreenWidth - 120 * kWidthBase, 40*kHeightBase) label:@"邮箱:" textField:@"请输入邮箱:"];
    [self.view addSubview:_emailbox];
    
    
    
#pragma mark - 密码
    _password = [[PKLTView alloc]initWithFrame:CGRectMake(_emailbox.frame.origin.x , _emailbox.frame.origin.y + _emailbox.frame.size.height + 20*kWidthBase, _emailbox.frame.size.width, 40*kHeightBase) label:@"密码:" textField:@"请输入密码:"];
    
    [self.view addSubview:_password];
    
#pragma mark - 忘记密码
    
    UIButton *missingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    missingButton.frame = CGRectMake(kScreenWidth - 180*kWidthBase, _password.frame.origin.y + _password.frame.size.height + 20*kHeightBase, 100*kWidthBase, 30*kHeightBase);
    
    
    UIImageView *missImageV = [[UIImageView alloc]initWithFrame:CGRectMake(10*kWidthBase, 5*kHeightBase, 20*kWidthBase, 20*kHeightBase)];
    missImageV.image = [UIImage imageNamed:@"yiwen"];
    [missingButton addSubview:missImageV];
    
    UILabel *missLabel = [[UILabel alloc]initWithFrame:CGRectMake(30*kWidthBase, 0, 70*kWidthBase, 30*kHeightBase)];
    missLabel.text = @"忘记密码?";
    missLabel.textColor = [UIColor lightGrayColor];
    missLabel.font = [UIFont systemFontOfSize:14];
    [missingButton addSubview:missLabel];
    [missingButton addTarget:self action:@selector(missButton:) forControlEvents:UIControlEventTouchUpInside];
    
    missingButton.alpha = 0;
    missImageV.alpha = 0;
    
    [self.view addSubview:missingButton];
    
    
#pragma mark ---------------动画展示上面的控件
    
    [UIView animateWithDuration:0.5 animations:^{
       
        _emailbox.frame = CGRectMake(60*kWidthBase, 260 * kHeightBase, kScreenWidth - 120 * kWidthBase, 40*kHeightBase);
        _password.frame = CGRectMake(_emailbox.frame.origin.x , _emailbox.frame.origin.y + _emailbox.frame.size.height + 20*kWidthBase, _emailbox.frame.size.width, 40*kHeightBase);
        
    } completion:^(BOOL finished) {
        missingButton.alpha = 1;
        missImageV.alpha = 1;
#pragma mark -登录按钮
        UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        loginButton.frame = CGRectMake(_emailbox.frame.origin.x, _password.frame.origin.y + _password.frame.size.height +  60*kHeightBase, _emailbox.frame.size.width, _emailbox.frame.size.height);
        
        loginButton.backgroundColor = [UIColor tanguolu];
        [loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [loginButton addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
        loginButton.alpha = 0;
        CGPoint center = loginButton.center;
        CGPoint startCenter = center;
        startCenter.x -= 100*kWidthBase;
        loginButton.center = startCenter;
        [self.view addSubview:loginButton];

        
        [UIView animateWithDuration:0.5 delay:0.35 usingSpringWithDamping:0 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{
            
            loginButton.alpha = 1;
            loginButton.center = center;
           
            
            
        } completion:^(BOOL finished) {
           
#pragma mark -合作伙伴
            UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(_emailbox.frame.origin.x, loginButton.frame.origin.y + loginButton.frame.size.height + 60*kHeightBase, _emailbox.frame.size.width, 0.5*kHeightBase)];
            
            lineLabel.backgroundColor = [UIColor lightGrayColor];
            [self.view addSubview:lineLabel];
            
            UILabel *partnersLabel = [[UILabel alloc]initWithFrame:CGRectMake(140*kWidthBase, loginButton.frame.origin.y + loginButton.frame.size.height + 40*kHeightBase, kScreenWidth - 280*kWidthBase, _emailbox.frame.size.height)];
            
            partnersLabel.text = @"合作伙伴登录片刻";
            partnersLabel.font = [UIFont systemFontOfSize:10];
            partnersLabel.textAlignment = NSTextAlignmentCenter;
            partnersLabel.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:partnersLabel];

            
#pragma mark - 图标
            NSArray *array = @[@"weibo",@"qq",@"douban",@"renren"];
            for (int i = 0; i < 4; i ++) {
                UIButton * partnersButton = [UIButton buttonWithType:UIButtonTypeCustom];
                partnersButton.frame = CGRectMake(lineLabel.frame.origin.x + 70*kWidthBase * i , partnersLabel.frame.size.height + partnersLabel.frame.origin.y + 20*kHeightBase, 30*kWidthBase, 30*kWidthBase);
                partnersButton.layer.cornerRadius = 30*kWidthBase / 2;
                partnersButton.layer.masksToBounds = YES;
                [partnersButton setBackgroundImage:[UIImage imageNamed:array[i]] forState:UIControlStateNormal];
                partnersButton.tag = 1111 + i;
                [partnersButton addTarget:self action:@selector(iconButton:) forControlEvents:UIControlEventTouchUpInside];
                partnersButton.alpha = 0;
                [self.view addSubview:partnersButton];
                
                CGPoint center = partnersButton.center;
                CGPoint startCenter = center;
                startCenter.y += 100;
                partnersButton.center = startCenter; // 先把cell的中心点上升200
                
                
                [UIView animateWithDuration:0.8 delay:0.5*i usingSpringWithDamping:0.4 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    
                    partnersButton.alpha = 1;
                    
                    partnersButton.center = center;
                    
                    
                } completion:^(BOOL finished) {
                    
#pragma mark  ---- 自定义导航栏
                    if (i == 3) {
                       
                        UIButton *registerButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
                        registerButton.frame = CGRectMake(kScreenWidth - 40*kWidthBase - 20*kWidthBase, 30 * kHeightBase, 50 * kWidthBase, 30 * kHeightBase);
                        [registerButton setTitle:@"注册" forState:(UIControlStateNormal)];
                        [registerButton setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
                        registerButton.titleLabel.font = [UIFont systemFontOfSize:14];
                        [registerButton addTarget:self action:@selector(registButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
                        [self.view addSubview:registerButton];
                        
                        registerButton.alpha = 0;
                        CGPoint center = registerButton.center;
                        CGPoint startCenter = center;
                        startCenter.y -= 80;
                        registerButton.center = startCenter;
                        
                        
                        
                        [UIView animateWithDuration:0.8 delay:0.05 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                            
                            registerButton.alpha = 1;
                            registerButton.center = center;
                            
                            
                        } completion:nil];
                        
                        
                        
                    }
         
                }];
                
            }
            
        }];
        
        
    }];
  
    
}

#pragma mark - 返回上一个界面
- (void)back:(UIButton *)button{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
  
}

#pragma mark - 注册按钮
- (void)registButtonClick:(UIButton *)button{
    NSLog(@"点击注册");
    
    PKRegistViewController *registVC = [[PKRegistViewController alloc]init];
   
    [self.navigationController pushViewController:registVC animated:YES];
}

#pragma mark - 忘记密码
- (void)missButton:(UIButton *)sender{
 
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://pianke.me/user/findpwd.php"]];
}

#pragma mark -合作伙伴图标
- (void)iconButton:(UIButton *)sender{
    
//    [[UIApplication sharedApplication]openURL:sender.tag - 1111];
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        // 获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
        }});
    
    //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
    [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
        NSLog(@"SnsInformation is %@",response.data);
        
    }];
    
    // 获取好友列表调用下面的方法,由于新浪官方限制，获取好友列表只能获取到30%好友
    [[UMSocialDataService defaultDataService] requestSnsFriends:UMShareToSina  completion:^(UMSocialResponseEntity *response){
        NSLog(@"SnsFriends is %@",response.data);
    }];
    
    // 删除授权调用下面的方法
    [[UMSocialDataService defaultDataService] requestUnOauthWithType:UMShareToSina  completion:^(UMSocialResponseEntity *response){
        NSLog(@"response is %@",response);
    }];
    
}

#pragma mark ---- 登陆按钮
- (void)login:(UIButton *)sender{
    
    
    [self loginPerson];
    
}



// 进行数据解析
- (void)loginPerson
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"63A94D37-33F9-40FF-9EBB-481182338873";
    parDic[@"email"] = _emailbox.textField.text;
    parDic[@"passwd"] = _password.textField.text;
    parDic[@"version"] = @"3.0.6";
    
    
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/user/login" parDic:parDic Method:POST finish:^(NSData *data) {
        
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *dataDic = dic[@"data"];
        
        if ([dataDic count] == 1) {
            
            NSLog(@"密码错误");
            if ([dataDic[@"msg"]isEqualToString:@"此邮箱还没有注册过"]) {

                DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"Sorry" contentText:@"此邮箱还没有注册过" leftButtonTitle:nil rightButtonTitle:@"Fine"];
                [alert show];

        }else if([dataDic[@"msg"]isEqualToString:@"邮箱格式错误，请重试！"]){

            DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"Sorry" contentText:@"邮箱格式错误，请重试!" leftButtonTitle:nil rightButtonTitle:@"Fine"];
            [alert show];

        } else if ([dataDic[@"msg"]isEqualToString:@"邮箱或密码错误，请重试！"]){

            DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"Sorry" contentText:@"邮箱或密码错误，请重试!" leftButtonTitle:nil rightButtonTitle:@"Fine"];
            [alert show];

            
        }
            
        }else {
            
            DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"Congratulations" contentText:@"登陆成功!" leftButtonTitle:nil rightButtonTitle:@"Fine"];
            [alert show];
            
            alert.rightBlock = ^() {
                
                _model = [[PKPersonModel alloc] init];
                
                [_model setValuesForKeysWithDictionary:dataDic];
                
                // 登陆成功后,把用户信息,保存到userDefaults中
                NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
                [userdefaults setObject:_model.auth forKey:@"auth"];
                [userdefaults setObject:_model.coverimg forKey:@"coverimg"];
                [userdefaults setObject:_model.icon forKey:@"icon"];
                [userdefaults setObject:_model.uid forKey:@"uid"];
                [userdefaults setObject:_model.uname forKey:@"uname"];
                [userdefaults setBool:YES forKey:@"状态"];
                // 字体变小: 登陆的时候,就把
                [userdefaults setInteger:100 forKey:@"网页比例"];
                [userdefaults setObject:@"day" forKey:@"日夜"];
                
                [userdefaults synchronize];
                // 发送通知,告诉,右侧界面,给控件赋值
                NSDictionary *dic = @{
                                      @"用户信息":_model
                                      
                                      };
                [[NSNotificationCenter defaultCenter]postNotificationName:@"用户信息" object:self userInfo:dic];
                [self dismissViewControllerAnimated:YES completion:nil];
                
            };
        }
        
                
    } error:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
    
  
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_emailbox.textField resignFirstResponder];
    [_password.textField resignFirstResponder];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
